package com.atguigu.spzx.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.exception.GuiguException;
import com.atguigu.spzx.model.dto.h5.UserLoginDto;
import com.atguigu.spzx.model.dto.h5.UserRegisterDto;
import com.atguigu.spzx.model.entity.user.UserBrowseHistory;
import com.atguigu.spzx.model.entity.user.UserCollect;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.h5.UserInfoVo;
import com.atguigu.spzx.user.mapper.UserInfoMapper;
import com.atguigu.spzx.user.service.UserInfoService;
import com.atguigu.spzx.utils.AuthContextUtils;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void register(UserRegisterDto userRegisterDto) {
//获取数据
        String username = userRegisterDto.getUsername();
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();

//        校验参数
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(nickName) ||
                StringUtils.isEmpty(code)
        ) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
//        校验验证码
//        用户名就是 phone ，当用户获取验证码时是通过phone获取，并存在redis里
//        todo 注释掉验证码
//        String codeValueRedis = redisTemplate.opsForValue().get("phone:code:" + username);
//        if(!code.equals(codeValueRedis)){
//            throw new GuiguException(ResultCodeEnum.VALIDATECODE_ERROR);
//        }


//        验证是否存在用户
        UserInfo userInfo = userInfoMapper.getByUsername(username);
        if (null != userInfo) {
//            存在用户名相同的用户 返回错误信息
            throw new GuiguException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }


//        保存用户
        userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setNickName(nickName);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setPhone(username);
        userInfo.setStatus(1);
        userInfo.setSex(0);
        userInfo.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        userInfoMapper.save(userInfo);
//        删除redis中的数据
        redisTemplate.delete("phone:code:" + username);
    }

    @Override
    public Object login(UserLoginDto userLoginDto) {
        String password = userLoginDto.getPassword();
        String username = userLoginDto.getUsername();
//        校验参数
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(username)) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
//        查询用户
        UserInfo userInfo = userInfoMapper.getByUsername(username);
        if (null == userInfo) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
//        校验密码
        String md5InputPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5InputPwd.equals(userInfo.getPassword())) {
            throw new GuiguException(ResultCodeEnum.LOGIN_ERROR);
        }
//        校验是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
//        存储到redis里
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:spzx:" + token, JSON.toJSONString(userInfo), 30, TimeUnit.DAYS);
        return token;
    }

    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
//        AuthContextUtils.getUserInfo();
        String userInfoJSON = redisTemplate.opsForValue().get("user:spzx:" + token);
        if(StringUtils.isEmpty(userInfoJSON)){
            throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
        }
        UserInfo userInfo = JSON.parseObject(userInfoJSON, UserInfo.class);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }

    @Override
    public void saveUserCollect(Long id) {

    }

    @Override
    public PageInfo<UserCollect> findUserBrowseHistoryPage(Integer page, Integer limit) {
        return null;
    }

    @Override
    public PageInfo<UserBrowseHistory> findUserCollectPage(Integer page, Integer limit) {
        return null;
    }

    @Override
    public void updatecancelCollect(Long skuId) {

    }

    @Override
    public void savecollect(Long skuId) {

    }

    @Override
    public Boolean findUserisCollect(Long skuId) {
        return null;
    }

    @Override
    public UserBrowseHistory getMostFrequentSkuId() {
        return null;
    }
}
